package com.study.rocket.order;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

/**
 * @author mjy(消息的生产者)
 * @date 2021/12/10
 * @description
 */
public class Producer {


    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("group2");
        producer.setNamesrvAddr("192.168.15.170:9876");
        //启动生产者
        producer.start();
        //获取订单
        List<OrderStep> orderSteps = OrderStep.bulidOrders();
        //发送消息
        for (OrderStep orderStep : orderSteps) {
            int count=0;
            Message message = new Message("orderTopic", "order", "i:"+count,orderStep.toString().getBytes());
            /**
             * 参数一消息对象
             * 参数二：消息队列选择器
             * 参数三：选择业务的一个标识
             */
            SendResult send = producer.send(message, new MessageQueueSelector() {
                /**
                 *
                 * @param list(队列集合)
                 * @param message(消息对象)
                 * @param arg(业务标识参数)
                 * @return
                 */
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object arg) {
                    Long orderId = (Long) arg;
                    long index = orderId % list.size();
                    System.out.println("index:"+index);
                    return list.get((int) index);
                }
            }, orderStep.getOrderId());
            System.out.println("当前线程："+Thread.currentThread().getName());
            System.out.println("消息发送"+send);
            count++;
        }

        producer.shutdown();
    }
}
